package com.example.web.webauth.dao;

import com.example.web.webauth.model.AuthorityDto;
import com.example.web.webauth.model.RoleDto;
import com.example.web.webauth.model.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Administrator
 * @version 1.0
 **/
@Repository
public class UserDao {

    @Autowired
    JdbcTemplate jdbcTemplate;

    //根据账号查询用户信息
    public UserDto getUserByUsername(String username) {
        String sql =
                " select u.* from `user` AS u " +
                        " JOIN company m ON u.company_id = m.company_id AND m.company_state >=0 " +
                        " where u.username = ? AND u.state >= 0 ";
//        String sql = "select * from `user` where username = ?";
        //连接数据库查询用户
        List<UserDto> list = jdbcTemplate.query(sql, new Object[]{username}, new BeanPropertyRowMapper<>(UserDto.class));
        if (list != null && list.size() == 1) {
            return list.get(0);
        }
        return null;
    }

    //根据用户id查询用户权限
    public List<String> findPermissionsByUserId(String userId) {
        String sql =
                " SELECT * FROM authority WHERE authority_id IN ( " +
                        "  SELECT authority_id FROM role_authority_relation WHERE role_id IN ( " +
                        "   SELECT role_id FROM user_role_relation WHERE user_id=? " +
                        "  ) " +
                        " )";

        List<AuthorityDto> list = jdbcTemplate.query(sql, new Object[]{userId}, new BeanPropertyRowMapper<>(AuthorityDto.class));
        List<String> permissions = new ArrayList<>();
        list.forEach(c -> permissions.add(c.getAuthorityName()));
        return permissions;
    }

    //根据账号查询用户信息
    public RoleDto getRoleByUserId(String userId) {
        String sql = " SELECT * FROM role WHERE role_id = ( " +
                " SELECT role_id FROM user_role_relation WHERE user_id=? " +
                " )";
        //连接数据库查询用户
        List<RoleDto> list = jdbcTemplate.query(sql, new Object[]{userId}, new BeanPropertyRowMapper<>(RoleDto.class));
        if (list != null && list.size() == 1) {
            return list.get(0);
        }
        return null;
    }

}
